<template>
  <div class="app-container">
    <!-- <el-card class="box-card"> -->
    <h3>新建商品</h3>
    <el-form v-loading="loading" ref="goods" :rules="rules" :model="goods" label-width="150px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="goods.goodsName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="goods.categoryId" placeholder="请选择">
          <el-option
            v-for="item in categoryList"
            :key="item.categoryId"
            :label="item.category"
            :value="item.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品图片" prop="goodsImageList">
        <pa-upload
          :action="action"
          :show-file-list="false"
          :limit="3"
          :headers="headers"
          :on-success="uploadPicUrl"
          :on-remove="onRemove"
          tip="建议商品图尺寸:750*420"
          list-type="picture-card"
          class="avatar-uploader"
          accept=".jpg, .jpeg, .png, .gif"
        />
      </el-form-item>
      <el-form-item label="商品详情" prop="detailMobileHtml">
        <vue-ueditor-wrap
          v-model="goods.detailMobileHtml"
          :config="ueditorConfig.config"
          @ready="ueditorConfig.ready"
        />
      </el-form-item>

      <el-form-item label="商品价格" prop="price" placeholder="请输入">
        <el-input-number v-model="goods.price" :min="0" :precision="2" />
      </el-form-item>
      <el-form-item label="商品库存" prop="stock" placeholder="请输入">
        <el-input-number v-model="goods.stock" :min="1" />
      </el-form-item>

      <el-form-item label="商品状态" prop="publishStatus">
        <el-radio-group v-model="goods.publishStatus">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">仓库</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否推荐" prop="recommendStatus">
        <el-radio-group v-model="goods.recommendStatus">
          <el-radio :label="1">推荐</el-radio>
          <el-radio :label="0">不推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关联课程" prop="courseId">
        <el-select v-model="goods.courseId" placeholder="请选择">
          <el-option
            v-for="item in courseList"
            :key="item.courseId"
            :label="item.courseName"
            :value="item.courseId"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="运费模版" prop="courseId">
        <el-select v-model="goods.templateId" placeholder="请选择">
          <el-option
            v-for="item in templateList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <div class="op-container">
        <el-button type="primary" @click="handlePublish('goods')">提交</el-button>
        <el-button @click="handleCancel('goods')">取消</el-button>
      </div>
    </el-form>
    <!-- </el-card> -->

    <!-- <el-card class="box-card">
      <h3>商品规格</h3>
      <el-row :gutter="20" type="flex" align="middle" style="padding:20px 0;">
        <el-col :span="10">
          <el-radio-group v-model="multipleSpec" @change="specChanged">
            <el-radio-button :label="false">默认标准规格</el-radio-button>
            <el-radio-button :label="true">多规格支持</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col v-if="multipleSpec" :span="10">
          <el-button :plain="true" type="primary" @click="handleSpecificationShow">添加</el-button>
        </el-col>
      </el-row>

      <el-table :data="specifications">
        <el-table-column property="specification" label="规格名"/>
        <el-table-column property="value" label="规格值">
          <template slot-scope="scope">
            <el-tag type="primary">
              {{ scope.row.value }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="picUrl" label="规格图片">
          <template slot-scope="scope">
            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">
          </template>
        </el-table-column>
        <el-table-column
          v-if="multipleSpec"
          align="center"
          label="操作"
          width="250"
          class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleSpecificationDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="specVisiable" title="设置规格">
        <el-form
          ref="specForm"
          :rules="rules"
          :model="specForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;">
          <el-form-item label="规格名" prop="specification">
            <el-input v-model="specForm.specification"/>
          </el-form-item>
          <el-form-item label="规格值" prop="value">
            <el-input v-model="specForm.value"/>
          </el-form-item>
          <el-form-item label="规格图片" prop="picUrl">
            <el-upload
              :action="uploadPath"
              :show-file-list="false"
              :headers="headers"
              :on-success="uploadSpecPicUrl"
              class="avatar-uploader"
              accept=".jpg,.jpeg,.png,.gif">
              <img v-if="specForm.picUrl" :src="specForm.picUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="specVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleSpecificationAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card>-->

    <!-- <el-card class="box-card">
      <h3>商品库存</h3>
      <el-table :data="products">
        <el-table-column property="value" label="货品规格">
          <template slot-scope="scope">
            <el-tag v-for="tag in scope.row.specifications" :key="tag">
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="price" width="100" label="货品售价"/>
        <el-table-column property="number" width="100" label="货品数量"/>
        <el-table-column property="url" width="100" label="货品图片">
          <template slot-scope="scope">
            <img v-if="scope.row.url" :src="scope.row.url" width="40">
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleProductShow(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="productVisiable" title="设置货品">
        <el-form
          ref="productForm"
          :model="productForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;">
          <el-form-item label="货品规格列" prop="specifications">
            <el-tag v-for="tag in productForm.specifications" :key="tag">
              {{ tag }}
            </el-tag>
          </el-form-item>
          <el-form-item label="货品售价" prop="price">
            <el-input v-model="productForm.price"/>
          </el-form-item>
          <el-form-item label="货品数量" prop="number">
            <el-input v-model="productForm.number"/>
          </el-form-item>
          <el-form-item label="货品图片" prop="url">
            <el-upload
              :action="uploadPath"
              :show-file-list="false"
              :headers="headers"
              :on-success="uploadProductUrl"
              class="avatar-uploader"
              accept=".jpg,.jpeg,.png,.gif">
              <img v-if="productForm.url" :src="productForm.url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="productVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleProductEdit">确定</el-button>
        </div>
      </el-dialog>
    </el-card>-->

    <!-- <el-card class="box-card">
      <h3>商品参数</h3>
      <el-button :plain="true" type="primary" @click="handleAttributeShow">添加</el-button>
      <el-table :data="attributes">
        <el-table-column property="attribute" label="商品参数名称"/>
        <el-table-column property="value" label="商品参数值"/>
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleAttributeDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="attributeVisiable" title="设置商品参数">
        <el-form
          ref="attributeForm"
          :model="attributeForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;">
          <el-form-item label="商品参数名称" prop="attribute">
            <el-input v-model="attributeForm.attribute"/>
          </el-form-item>
          <el-form-item label="商品参数值" prop="value">
            <el-input v-model="attributeForm.value"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="attributeVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleAttributeAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card>-->

    <!-- <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">上架</el-button>
    </div>-->
  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.op-container {
  padding-left: 100px;
}
</style>

<script>
import ueditorConfig from '@/config/ueditorConfig'
import { listCategory } from '@/api/category'
import { getCourseList } from '@/api/course'
import { publishGoods, upGoods } from '@/api/goods'
// import { createStorage } from '@/api/storage'
import { getFreightList } from '@/api/freight/index'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import upload from '@/components/Upload'
export default {
  name: 'GoodsCreate',
  components: { Editor, 'pa-upload': upload },

  data() {
    var validImg = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请上传图片'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      ueditorConfig: ueditorConfig,
      action: `${process.env.BASE_API}/vms/v1/image/upload`,
      // newKeywordVisible: false,
      // newKeyword: '',
      // keywords: [],
      // brandList: [],
      // specVisiable: false,
      // specForm: { specification: '', value: '', picUrl: '' },
      // multipleSpec: false,
      // specifications: [{ specification: '规格', value: '标准', picUrl: '' }],
      // productVisiable: false,
      // productForm: {
      //   id: 0,
      //   specifications: [],
      //   price: 0.0,
      //   number: 0,
      //   url: ''
      // },
      // products: [
      //   { id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }
      // ],
      // attributeVisiable: false,
      // attributeForm: { attribute: '', value: '' },
      // attributes: [],

      goods: {
        goodsName: '',
        categoryId: '',
        detailMobileHtml: '',
        goodsImageList: [],
        price: '',
        publishStatus: 1,
        recommendStatus: 0,
        courseId: '',
        stock: '',
        templateId: ''
      },
      rules: {
        goodsName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ],
        detailMobileHtml: [
          { required: true, message: '商品详情不能为空', trigger: 'blur' }
        ],
        goodsImageList: [
          { required: true, validator: validImg, trigger: 'blur' }
        ],
        price: [
          { required: true, message: '商品价格不能为空', trigger: 'blur' }
        ],
        stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
      },
      categoryList: [],
      courseList: [],
      templateList: []
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    // this.init()
    this.getCategory()
    this.getCourseList()
    this.getTemplateList()
  },

  methods: {
    getTemplateList() {
      getFreightList({ index: 0, size: 100 })
        .then(response => {
          this.templateList = response.data.data.content
        })
        .catch(() => {
          this.categoryList = []
        })
    },
    getCategory() {
      listCategory({ index: 0, size: 100 })
        .then(response => {
          this.categoryList = response.data.data.content
        })
        .catch(() => {
          this.categoryList = []
        })
    },
    getCourseList() {
      getCourseList({ index: 0, size: 100 })
        .then(response => {
          this.courseList = response.data.data.content
        })
        .catch(() => {
          this.courseList = []
        })
    },

    handleCancel: function(formName) {
      this.$refs[formName].resetFields()
    },
    handlePublish: function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loading = true
          const params = this.goods
          // const reg = new RegExp(
          //   `<img src=`,
          //   'g',
          // )
          // params.detailMobileHtml = params.detailMobileHtml.replace(
          //   reg,
          //   `<img style="width:100%;height:auto;display:block" src=`,
          // )
          publishGoods(params)
            .then(res => {
              this.loading = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
              if (params.publishStatus === 1) {
                this.handleUp(res.data.data.id)
              } else {
                this.$router.push({ name: 'goodsList' })
              }
            })
            .catch(response => {
              this.loading = false
              MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                confirmButtonText: '确定',
                type: 'error'
              })
            })
        }
      })
    },
    uploadPicUrl: function(response) {
      this.$refs['goods'].clearValidate('goodsImageList')
      this.goods.goodsImageList.push({
        name: response.name,
        url: response.data.fileUrl
      })
    },
    onRemove(file, fileList) {
      this.goods.goodsImageList.forEach((item, index) => {
        if (file.data.fileUrl === item.url) {
          this.goods.goodsImageList.splice(index, 1)
        }
      })
    },
    handleUp(id) {
      upGoods(id)
        .then(res => {
          this.$router.push({ name: 'goodsList' })
        })
        .catch(error => {
          this.$message.error(error.data.respCode.message)
        })
    }
    // uploadOverrun: function() {
    //   this.$message({
    //     type: 'error',
    //     message: '上传文件个数超出限制!最多上传5张图片!'
    //   })
    // },
    // handleGalleryUrl(response, file, fileList) {
    //   if (response.errno === 0) {
    //     this.goods.gallery.push(response.data.url)
    //   }
    // },
    // handleRemove: function(file, fileList) {
    //   for (var i = 0; i < this.goods.gallery.length; i++) {
    //     // 这里存在两种情况
    //     // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
    //     //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
    //     // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
    //     var url
    //     if (file.response === undefined) {
    //       url = file.url
    //     } else {
    //       url = file.response.data.url
    //     }

    //     if (this.goods.gallery[i] === url) {
    //       this.goods.gallery.splice(i, 1)
    //     }
    //   }
    // },
    // specChanged: function(label) {
    //   if (label === false) {
    //     this.specifications = [
    //       { specification: '规格', value: '标准', picUrl: '' }
    //     ]
    //     this.products = [
    //       { id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }
    //     ]
    //   } else {
    //     this.specifications = []
    //     this.products = []
    //   }
    // },
    // uploadSpecPicUrl: function(response) {
    //   this.specForm.picUrl = response.data.url
    // },
    // handleSpecificationShow() {
    //   this.specForm = { specification: '', value: '', picUrl: '' }
    //   this.specVisiable = true
    // },
    // handleSpecificationAdd() {
    //   var index = this.specifications.length - 1
    //   for (var i = 0; i < this.specifications.length; i++) {
    //     const v = this.specifications[i]
    //     if (v.specification === this.specForm.specification) {
    //       if (v.value === this.specForm.value) {
    //         this.$message({
    //           type: 'warning',
    //           message: '已经存在规格值:' + v.value
    //         })
    //         this.specForm = {}
    //         this.specVisiable = false
    //         return
    //       } else {
    //         index = i
    //       }
    //     }
    //   }

    //   this.specifications.splice(index + 1, 0, this.specForm)
    //   this.specVisiable = false

    //   this.specToProduct()
    // },
    // handleSpecificationDelete(row) {
    //   const index = this.specifications.indexOf(row)
    //   this.specifications.splice(index, 1)
    //   this.specToProduct()
    // },
    // specToProduct() {
    //   if (this.specifications.length === 0) {
    //     return
    //   }
    //   // 根据specifications创建临时规格列表
    //   var specValues = []
    //   var spec = this.specifications[0].specification
    //   var values = []
    //   values.push(0)

    //   for (var i = 1; i < this.specifications.length; i++) {
    //     const aspec = this.specifications[i].specification

    //     if (aspec === spec) {
    //       values.push(i)
    //     } else {
    //       specValues.push(values)
    //       spec = aspec
    //       values = []
    //       values.push(i)
    //     }
    //   }
    //   specValues.push(values)

    //   // 根据临时规格列表生产货品规格
    //   // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
    //   var productsIndex = 0
    //   var products = []
    //   var combination = []
    //   var n = specValues.length
    //   for (var s = 0; s < n; s++) {
    //     combination[s] = 0
    //   }
    //   var index = 0
    //   var isContinue = false
    //   do {
    //     var specifications = []
    //     for (var x = 0; x < n; x++) {
    //       var z = specValues[x][combination[x]]
    //       specifications.push(this.specifications[z].value)
    //     }
    //     products[productsIndex] = {
    //       id: productsIndex,
    //       specifications: specifications,
    //       price: 0.0,
    //       number: 0,
    //       url: ''
    //     }
    //     productsIndex++

    //     index++
    //     combination[n - 1] = index
    //     for (var j = n - 1; j >= 0; j--) {
    //       if (combination[j] >= specValues[j].length) {
    //         combination[j] = 0
    //         index = 0
    //         if (j - 1 >= 0) {
    //           combination[j - 1] = combination[j - 1] + 1
    //         }
    //       }
    //     }
    //     isContinue = false
    //     for (var p = 0; p < n; p++) {
    //       if (combination[p] !== 0) {
    //         isContinue = true
    //       }
    //     }
    //   } while (isContinue)

    //   this.products = products
    // },
    // handleProductShow(row) {
    //   this.productForm = Object.assign({}, row)
    //   this.productVisiable = true
    // },
    // uploadProductUrl: function(response) {
    //   this.productForm.url = response.data.url
    // },
    // handleProductEdit() {
    //   for (var i = 0; i < this.products.length; i++) {
    //     const v = this.products[i]
    //     if (v.id === this.productForm.id) {
    //       this.products.splice(i, 1, this.productForm)
    //       break
    //     }
    //   }
    //   this.productVisiable = false
    // },
    // handleAttributeShow() {
    //   this.attributeForm = {}
    //   this.attributeVisiable = true
    // },
    // handleAttributeAdd() {
    //   this.attributes.unshift(this.attributeForm)
    //   this.attributeVisiable = false
    // },
    // handleAttributeDelete(row) {
    //   const index = this.attributes.indexOf(row)
    //   this.attributes.splice(index, 1)
    // }
  }
}
</script>
